package org.snia.cdmi.model;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.JsonToken;
import org.snia.cdmi.LinkSitePermission;

/**
 * Represents an container.
 */
public class Container extends BaseContainer{
    private static final long serialVersionUID = -8646831898339939580L;
   
    private List<String> sites = null;
    
    private LinkSitePermission permission = null;
    
    private Map<String, String> metadata = null;    
    
    private AccessControlList acl = null;

    /**
     * @see java.lang.Object#toString()
     */
    @Override
	public String toString() {
        return "Container [name=" + getName()
                + ", creationDate=" + getCreationDate();
    }

    
    public List<String> getSites() {
        return sites;
    }

    public void setSites(List<String> sites) {
        this.sites = sites;
    }
    
    public LinkSitePermission getPermission() {
        return permission;
    }

    public void setPermission(LinkSitePermission permission) {
        this.permission = permission;
    }
    
    public Map<String, String> getUserMetadata() {
        return this.metadata;
    }
    
    public void setUserMetadata(Map<String, String> metadata) {
        this.metadata = metadata;
    }
	
	/**
	 * @param acl the acl to set
	 */
	public void setAccessControlList(AccessControlList acl) {
		this.acl = acl;
	}

	/**
	 * @return the acl
	 */
	public AccessControlList getAccessControlList() {
		return acl;
	}

	public void fromJson(byte[] jsonBytes) throws JsonParseException, IOException {
		
//		XStream xstream = new XStream(new JettisonMappedXmlDriver());
//		xstream.alias("acl", Map.class);
//		Map<String, String> acl = (HashMap<String, String>)xstream.fromXML(jsonBytes.toString());
//		System.out.println(acl.size());
		
		JsonFactory f = new JsonFactory();
		JsonParser jp = f.createJsonParser(jsonBytes);
		@SuppressWarnings("unused")
		JsonToken tolkein = jp.nextToken();//START_OBJECT
		while ((tolkein = jp.nextToken()) != JsonToken.END_OBJECT) {
			String key = jp.getCurrentName();
			if ("acl".equals(key)) {//process acl
				tolkein = jp.nextToken();
				while ((tolkein = jp.nextToken()) != JsonToken.END_OBJECT) {
					key = jp.getCurrentName();
					tolkein = jp.nextToken();
					String value = jp.getText();
					System.out.println("   Key = " + key + " : Value = " + value);
					if(this.acl == null){
						this.acl = new AccessControlList();
					}
					this.acl.grantPermission(new KeyGrantee(key), Permission.fromValue(value));
					//jp.nextToken();
				}//while	
			} else {
				//忽略
			}
		}
	}
}
